package com.grgbanking.it.project.service.impl;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.grgbanking.it.base.WXConnectionService;
import com.grgbanking.it.common.json.JSONHelper;
import com.grgbanking.it.common.util.DateUtil;
import com.grgbanking.it.common.util.HibernateUtil;
import com.grgbanking.it.project.component.WXTaskMessageCreator;
import com.grgbanking.it.project.dao.ITaskDao;
import com.grgbanking.it.project.dao.ITaskResultDao;
import com.grgbanking.it.project.entity.Task;
import com.grgbanking.it.project.entity.TaskResult;
import com.grgbanking.it.project.service.ITaskService;

/**
 * 日常任务管理
 * 
 * TaskService
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2015-1-23 下午4:16:35
 * 
 * @version 1.0.0
 *
 */
@Service
public class TaskService extends WXConnectionService implements ITaskService {
	@Autowired
	private ITaskDao<Task, Integer> taskDao;
	@Autowired
	private ITaskResultDao<TaskResult, Integer> taskResultDao;
	@Autowired
	private WXTaskMessageCreator messageCreator;
	
	@PostConstruct
	public void initMessageCreator() {
		super.setMessageCreator(messageCreator);
	}
	/**
	 * 保存或者更新
	 * saveOrUpdate
	 * 
	 * @param entity
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public void saveOrUpdate(Task task) throws Exception {
		task.setState(1);
		task.setCreateTime(DateUtil.getInstance().now());
		taskDao.saveOrUpdate(task);
	}
	@Override
	public void delete(Integer id) throws Exception {
		String hql = HibernateUtil.createVirtualDeleteHQL(Task.class, id);
		taskDao.executeHQL(hql);
	}
	/**
	 * 获取任务到页面日历中
	 * findJsonForCalender
	 * 
	 * @param start
	 * @param end
	 * @param userId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public String findJsonForCalender(String start,String end,String userId)
			throws Exception {
		StringBuffer hql = new StringBuffer("from Task t where t.state<>0 and t.type<>5 ");
		hql.append("and t.username='").append(userId).append("' and (t.type=2");
		hql.append(" or t.start between '").append(start).append("' and '").append(end).append("' or t.end between '").append(start).append("' and '").append(end).append("')");
	
		List<Task> tasks = taskDao.findByHql(hql.toString());
		
		return JSONHelper.converList(tasks);
	}
	/**
	 * 查找一天的任务
	 * findByDaily
	 * 
	 * @param date
	 * @param userId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public String findByDaily(String date, String userId) throws Exception {
		StringBuffer sql = this.createSQLByDate(date);
		sql.append(" and t.username='").append(userId).append("'");
		return JSONHelper.converList(taskDao.listBySQL(sql.toString()));
	}
	/**
	 * 获取部门所有人的任务信息
	 * findToTeam
	 * 
	 * @param date
	 * @param deptId
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public String findToTeam(String date, String deptId) throws Exception {
		StringBuffer sql = this.createSQLByDate(date);
		sql.append(" and t.departmentId=").append(deptId);
		sql.append(" order by t.username");
		return JSONHelper.converList(taskDao.listBySQL(sql.toString()));
	}
	/**
	 * 获取当天的任务SQL
	 * createSQLByDate
	 * 
	 * @param date
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	private StringBuffer createSQLByDate(String date){
		if(StringUtils.isEmpty(date)){
			date = DateUtil.getInstance().today("yyyy-MM-dd");
		}
		StringBuffer sql = new StringBuffer("select ");
		sql.append("\nt.id,t.createTime,t.content,t.type,t.start,t.end,t.departmentId,t.departmentName,t.username,t.trueName,");
		sql.append("\nt.projectId,r.result,r.duration,r.finishTime,t.require_ `require`,");
		sql.append("\ncase when t.type=2 and r.finishTime is not null then 3 else t.state end state");
		sql.append("\nfrom task t left join task_result r  on t.id=r.task_id  ");
		sql.append("\nand (t.type<>2 or (t.type=2 and r.finishTime like '").append(date).append("%'))");
		sql.append("\nwhere (t.state<>0 or r.finishTime is not null) and t.type<>5 and (t.type=2 or '").append(date).append("' between t.start and t.end or t.start like '");
		sql.append(date).append("%' or t.end like '").append(date).append("%')");
		return sql;
	}
	/**
	 * 直接完成
	 * updateFinish
	 * 
	 * @param id 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public void updateDirectFinish(Integer id) {
		Task task = taskDao.findById(id);
		
		TaskResult result = new TaskResult();
		result.setTask(task);
		result.setFinishTime(DateUtil.getInstance().now());
		task.setState(this.getState(task,result.getFinishTime()));
		
		taskResultDao.save(result);
		taskDao.update(task);
	}
	/**
	 * 延期到明天
	 * updatePostponeToTomorrow
	 * 
	 * @param id 
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public void updatePostponeToTomorrow(Integer id) throws Exception {
		Task task = this.getPostponeTask(id, DateUtil.getInstance().tomorrow());
		taskDao.update(task);
	}
	
	/**
	 * 处理操作
	 * (完成或延期)
	 * updateHandle
	 * 
	 * @param id
	 * @param data 
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public void updateHandle(Integer id, TaskResult data) throws Exception {
		Task task = null;
		if(data.getEnd() == null){
			task = taskDao.findById(id);
			data.setTask(task);
			data.setFinishTime(DateUtil.getInstance().now());
			taskResultDao.save(data);
			task.setState(this.getState(task,data.getFinishTime()));
		}else{
			task = this.getPostponeTask(id, data.getEnd());
		}
		
		taskDao.update(task);
	}
	/**
	 * 获取延期的任务
	 * getPostponeTask
	 * 
	 * @param id
	 * @param postponeTime
	 * @return 
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	private Task getPostponeTask(Integer id,Timestamp postponeTime) throws Exception{
		Task task = taskDao.findById(id);
		if(task.getType() == 2){
			throw new Exception("日常工作不需要做延迟操作");
		}else if(task.getEnd().after(postponeTime)){
			throw new Exception("计划结束时间比延迟的时间晚，不需要做延迟操作");
		}
		task.setState(2);
		task.setEnd(postponeTime);
		
		return task;
	}
	/**
	 * 获取状态
	 * getState
	 * 
	 * @param task
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	private Integer getState(Task task,Timestamp finishTime){
		Integer state = 4;
		if(task.getType() == 2){
			//日常工作不修改状态
			state = task.getState();
		}else if(task.getState() == 1){
			state = 3;
			if(finishTime.after(task.getEnd())){
				 state = 4;
			}
		}
		
		return state;
	}
	

}
